<?php
/**
 * Created by PhpStorm.
 * User: LiuTao
 * Date: 2018/11/12
 * Time: 16:27
 */

class UdpServer
{
    protected $addr = '127.0.0.1';
    protected $port = 10000;

    public function start()
    {
        if (($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) == FALSE) {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);
            $this->error("创建socekt失败: [$errorcode] $errormsg");
        }
        $this->info('socket 创建成功...');

        // 绑定到 ip 端口
        if (!socket_bind($socket, $this->addr, $this->port)) {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);
            $this->error("bind socket失败: [$errorcode] $errormsg");
        }
        $this->info('socket bind成功...');
        while (true) {
            $this->info("Waiting for data ... \n");
            //Receive
            $r = socket_recvfrom($socket, $buf, 2048, 0, $remote_ip, $remote_port);
            $this->info("$remote_ip : $remote_port -- " . $buf);

            // 不需要返回给客户端任何消息, 继续循环
        }
        socket_close($socket);
    }

    protected function info($msg)
    {
        echo $msg . PHP_EOL;
    }

    protected function error($msg)
    {
        echo $msg . PHP_EOL;
        exit();
    }
}

$client=new UdpServer();
$client->start();